package com.tiger.poker.util;


import com.tiger.poker.entity.Game21Vo;
import com.tiger.poker.entity.Player;
import lombok.extern.slf4j.Slf4j;

import javax.websocket.Session;
import java.util.Set;

/**
 * The type Web scoket service.
 *
 * @author joy
 */
@Slf4j
public class WebSocketUtil {

    /**
     * Send message.
     *
     * @param player        the battle vo
     * @param messageObject the message object
     */
    public static void sendMessage(Player player, Object messageObject) {
        if (player == null) {
            return;
        }
        Session battleVOSession = player.getSession();
        if (battleVOSession == null) {
            return;
        }
        try {
            if (messageObject instanceof String) {
                player.getSession().getBasicRemote().sendText((String) messageObject);
            } else {
                player.getSession().getBasicRemote().sendObject(messageObject);
            }
            log.info("send message to {}, content is {}", player.getName(), messageObject);
        } catch (Exception e) {
            log.error("send message error", e);
        }
    }

    /**
     * Send message.
     *
     * @param session       the session
     * @param messageObject the message object
     */
    public static void sendMessage(Session session, Object messageObject) {
        if (session == null) {
            return;
        }

        try {
            if (messageObject instanceof String) {
                session.getBasicRemote().sendText((String) messageObject);
            } else {
                session.getBasicRemote().sendObject(messageObject);
            }
            log.info("send message to {}, content is {}", session.getId(), messageObject);
        } catch (Exception e) {
            log.error("send message error", e);
        }
    }

    /**
     * Send message batch.
     *
     * @param fightSet the fight set
     * @param message  the message
     */
    public static <T extends Player> void sendMessageBatch(Set<T> fightSet, String message) {
        fightSet.forEach(battleVO -> sendMessage(battleVO.getSession(), message));
    }


    /**
     * Send message batch.
     *
     * @param fightSet the fight set
     * @param message  the message
     */
    public static <T extends Game21Vo> void sendMessageBatch21(Set<T> fightSet, String message) {
        fightSet.forEach(battleVO -> sendMessage(battleVO.getSession(), message));
    }
}
